package com.cart.controller;

import com.cart.exception.MsgException;
import com.cart.service.CartService;
import com.common.VO.SysResult;
import com.common.domain.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-02 14:19
 * @description
 * @copyright 2021
 */
@RestController
@RequestMapping("/cart")
public class CartController {

  @Autowired private CartService cartService;
  /**
   * 购物车中的商品查询
   *
   * @param userId 用户编号
   * @return 购物车中的商品
   */
  @GetMapping("/manage/query")
  @ResponseBody
  public List<Cart> queryCart(@RequestParam("userId") String userId) {
    return cartService.queryCart(userId);
  }
  /**
   * 加入购物车
   *
   * @param cart 购物车
   * @return vo
   */
  @PostMapping("/manage/save")
  @ResponseBody
  public SysResult saveCart(Cart cart) {
    try {
      cartService.addCart(cart);
      return SysResult.ok();
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
  /**
   * 更新购物车
   *
   * @param cart 新的购物车数据
   * @return vo
   */
  @PutMapping("/manage/update")
  @ResponseBody
  public SysResult updateCart(Cart cart) {
    try {
      cartService.updateCart(cart);
      return SysResult.ok();
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
  /**
   * 删除购物车
   *
   * @param cart 购物车数据
   * @return vo
   */
  @DeleteMapping("/manage/delete")
  @ResponseBody
  public SysResult deleteCart(Cart cart) {
    try {
      cartService.deleteCart(cart);
      return SysResult.ok();
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
  /**
   * 查询指定商品价格
   *
   * @param productId 商品id
   * @param userId 用户id
   * @return 总价格
   */
  @GetMapping("/manage/totalMoney")
  @ResponseBody
  public SysResult totalMoney(
      @RequestParam("productId") String productId,
      @RequestParam("productNums") String productNums,
      @RequestParam("userId") String userId) {
    try {
      Double money = cartService.totalPrice(productId, productNums, userId);
      return SysResult.ok(money);
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
}
